﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using TwitterApp;
using Hammock.Authentication.OAuth;
using Hammock.Web;
using Hammock;
using Puddy.Utils;
using System.Text;

namespace Puddy.UserControls
{
    public partial class TwitterLoginPage : PhoneApplicationPage
    {
        String OAuthTokenKey_twitter;
        String tokenSecret_twitter;

        string accessToken_twitter = string.Empty;
        string accessTokenSecret_twitter = string.Empty;

        string userID_twitter = string.Empty;
        string userScreenName_twitter = string.Empty;


        public TwitterLoginPage()
        {
            InitializeComponent();
        }


        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            
            if (NavigationContext.QueryString.TryGetValue("oauth_token", out OAuthTokenKey_twitter))
            {
                
            }
            
            if (NavigationContext.QueryString.TryGetValue("oauth_token_secret", out tokenSecret_twitter))
            {

            }

            var authorizeUrl = TwitterSettings.AuthorizeUri + "?oauth_token=" + OAuthTokenKey_twitter;
            webBrowser.Navigate(new Uri(authorizeUrl));
        }


        

        private void webBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            this.webBrowser.Navigated -= webBrowser_Navigated;
        }

        private void webBrowser_Navigating(object sender, NavigatingEventArgs e)
        {
            if (e.Uri.ToString().StartsWith(TwitterSettings.CallbackUri))
            {
                var AuthorizeResult = HelperMethods.GetQueryParameters(e.Uri.ToString());
                var VerifyPin = AuthorizeResult["oauth_verifier"];
                

                //We now have the Verification pin
                //Using the request token and verification pin to request for Access tokens

                var AccessTokenQuery = oAuthHelper.GetAccessTokenQuery(
                                                                         OAuthTokenKey_twitter,     //The request Token
                                                                         tokenSecret_twitter,       //The request Token Secret
                                                                         VerifyPin         // Verification Pin
                                                                        );

                AccessTokenQuery.QueryResponse += new EventHandler<WebQueryResponseEventArgs>(AccessTokenQuery_QueryResponse);
                AccessTokenQuery.RequestAsync(TwitterSettings.AccessTokenUri, null);

                //this.objAuthorizeBrowserControl.Visibility = Visibility.Collapsed;
                NavigationService.GoBack();
            }
        }

        void AccessTokenQuery_QueryResponse(object sender, WebQueryResponseEventArgs e)
        {
            try
            {
                var parameters = HelperMethods.GetQueryParameters(e.Response);
                accessToken_twitter = parameters["oauth_token"];
                accessTokenSecret_twitter = parameters["oauth_token_secret"];
                userID_twitter = parameters["user_id"];
                userScreenName_twitter = parameters["screen_name"];

                HelperMethods.SetKeyValue<string>("AccessToken", accessToken_twitter);
                HelperMethods.SetKeyValue<string>("AccessTokenSecret", accessTokenSecret_twitter);
                HelperMethods.SetKeyValue<string>("ScreenName", userScreenName_twitter);

                postTweetter();

            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show(ex.Message);
                });
            }
        }



        private void postTweetter()
        {


            var credentials = new OAuthCredentials
            {
                Type = OAuthType.ProtectedResource,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
                ConsumerKey = TwitterSettings.consumerKey,
                ConsumerSecret = TwitterSettings.consumerKeySecret,
                Token = this.accessTokenSecret_twitter,
                TokenSecret = this.accessTokenSecret_twitter,
                Version = "1.0"
            };

            var restClient = new RestClient
            {
                Authority = TwitterSettings.StatusUpdateUrl,
                HasElevatedPermissions = true,
                Credentials = credentials,
                Method = WebMethod.Post
            };

            restClient.AddHeader("Content-Type", "application/x-www-form-urlencoded");

            // Create a Rest Request and fire it
            var restRequest = new RestRequest
            {
                Path = "1/statuses/update.xml?status=" + Constants.TEXT_TO_POST + " on " + DateTime.Now.ToString("")
            };

            var ByteData = Encoding.UTF8.GetBytes(Constants.TEXT_TO_POST + " on " + DateTime.Now.ToString(""));
            restRequest.AddPostContent(ByteData);
            restClient.BeginRequest(restRequest, new RestCallback(PostTweetRequestCallback));
        }

        private void PostTweetRequestCallback(RestRequest request, Hammock.RestResponse response, object obj)
        {
            Dispatcher.BeginInvoke(() =>
            {
                MessageBox.Show(Constants.TEXT_POST_OK);
            });
        }
    }
}